package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.entity.DormitoryAdmin;
import org.example.entity.SystemAdmin;
import org.example.form.RuleForm;
import org.example.mapper.DormitoryAdminMapper;
import org.example.mapper.SystemAdminMapper;
import org.example.service.SystemAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.util.JwtUtils;
import org.example.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-10-31
 */
@Service
public class SystemAdminServiceImpl extends ServiceImpl<SystemAdminMapper, SystemAdmin> implements SystemAdminService {

    @Autowired
    private SystemAdminMapper systemAdminMapper;
    @Override
    public ResultVO login(RuleForm ruleForm) {
        //判断用户名是否存在
        QueryWrapper<SystemAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",ruleForm.getUsername());
        SystemAdmin systemAdmin = this.systemAdminMapper.selectOne(queryWrapper);
        ResultVO resultVO = new ResultVO();
        if (systemAdmin==null){
            resultVO.setCode(-1);
        }else {
            //判断密码是否正确
            if (!systemAdmin.getPassword().equals(ruleForm.getPassword())) {
                resultVO.setCode(-2);
            }else {
                //登陆成功，生成token令牌，下发令牌
                    Map<String, Object> claims = new HashMap<>();
                    claims.put("id", systemAdmin.getId());
                    claims.put("name", systemAdmin.getName());
                    claims.put("username", systemAdmin.getUsername());
                    String token = JwtUtils.generateJwt(claims);

                resultVO.setCode(0);
                resultVO.setMsg(token);
                resultVO.setData(systemAdmin);
            }
        }
        return resultVO;
    }
}
